/**
 * create by Michael.hong 2016.11.10
 */

class AjaxPromist {
    send(url,type,data) {
        return new Promise((resolve,reject) => {
            try{
                let xhr = new XMLHttpRequest() || window.ActiveXObject('Microsoft xmlhttp');
                xhr.timeout = 30000;
                xhr.ontimeout = function() {
                    console.log('The request is timed out!!!');
                }
                xhr.onreadystatechange = function() {
                    if(xhr.responseText) {
                        let res = JSON.parse(xhr.responseText);
                        if(xhr.readyState == 4 && xhr.status == 200){
                            resolve(res);
                        }else {

                        }
                    }
                }
                xhr.open(type,url,true);
                xhr.send(data = null ? null : String(data));
            } catch(e) {
                reject(e);
            }
        });
    }
}

export default {
    get: function(url,data) {
        return new AjaxPromist().send(url,'get',null);
    },
    post: function(url,data) {
        return new AjaxPromist().send(url,'post',data || {});
    }
}


